﻿using AMAP.Domain;
using AMAP.ServiceClasses.Common;
using AMAP.ServiceInterfaces;
using AMAP.ServiceInterfaces.Common;
using System;
using System.Linq;
using System.Text.RegularExpressions;
using ExternalOffer = AMAP.Areas.Admin.Models.Basket.AdminBasketCreateViewModel.ExternalOffer;
using System.Collections.Generic;

namespace AMAP.ServiceClasses
{
    public class ProductService : BaseRepositoryService<Product>, IProductService
    {
        public ProductService(IDatabaseFactory databaseFactory)
            : base(databaseFactory)
        {
        }

        public IList<Product> GetAllFruits()
        {
            return dataContext.ProductSet.Where(p => (p.Fruit == true)).ToList<Product>();
        }

        public IList<Product> GetAllVegetables()
        {
            return dataContext.ProductSet.Where(p => (p.Vegetable == true)).ToList<Product>();
        }

        public IList<Product> GetAllOthers()
        {
            return dataContext.ProductSet.Where(p => (p.Other == true)).ToList<Product>();
        }

        public Product GetByExternalOffer(ExternalOffer Offer)
        {
            string SearchedName = Offer.Name.Substring(0, Offer.Name.IndexOf("(") - 1);
            // Construction of the regex that would search for a mathc in existing products names
            string Pattern = "";
            var Words = SearchedName.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (Words.Length == 1)
                Pattern += SearchedName;
            else
                foreach (string word in Words)
                    if (word.Length > 1)
                        Pattern += "(?=.*" + word + ".*)";
            Pattern += "";
            Regex Regex = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);

            // Lets search for a match
            var res = from p in this.dataContext.ProductSet.AsEnumerable()
                      where Regex.IsMatch(p.Name)
                      select p;

            Product ExistingProduct = null;
            int resc = res.Count();
            try { ExistingProduct = res.FirstOrDefault(); }
            catch (Exception) { }

            // Lets check if we have a match
            if (ExistingProduct != null)
                return ExistingProduct;
            else // No result, we create a new Product
            {
                Product NewProduct = new Product
                {
                    Name = SearchedName,
                    Fruit = false,
                    Vegetable = false,
                    Other = false,
                    ShelfLife = 7
                };
                this.AddWithoutSaving(NewProduct);
                return NewProduct;
            }
        }
    }
}
